package com.ruoyi.hrmanagement.controller;

import java.io.InputStream;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelReader;
import com.ruoyi.hrmanagement.bean.ResponseData;
import com.ruoyi.hrmanagement.bean.ResultCode;
import com.ruoyi.hrmanagement.mapper.ContractWorkerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.hrmanagement.domain.ContractWorker;
import com.ruoyi.hrmanagement.service.IContractWorkerService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 合同工Controller
 * 
 * @author wjj
 * @date 2024-09-13
 */
@RestController
@RequestMapping("/contractworker")

public class ContractWorkerController extends BaseController {
    @Autowired
    private IContractWorkerService contractWorkerService;

    @Autowired
    private ContractWorkerMapper contractWorkerMapper;

    /**
     * 查询合同工列表
     */
    @RequiresPermissions("hrmanagement:contractworker:list")
    @GetMapping("/list")
    public TableDataInfo list(ContractWorker contractWorker) {
        startPage();
        List<ContractWorker> list = contractWorkerService.selectContractWorkerList(contractWorker);
        return getDataTable(list);
    }

    /**
     * 导出合同工列表
     */
    @RequiresPermissions("hrmanagement:contractworker:export")
    @Log(title = "合同工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractWorker contractWorker) {
        List<ContractWorker> list = contractWorkerService.selectContractWorkerList(contractWorker);
        ExcelUtil<ContractWorker> util = new ExcelUtil<ContractWorker>(ContractWorker.class);
        util.exportExcel(response, list, "合同工数据");
    }

    /**
     * 获取合同工详细信息
     */
    @RequiresPermissions("hrmanagement:contractworker:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(contractWorkerService.selectContractWorkerById(id));
    }

    /**
     * 新增合同工
     */
    @RequiresPermissions("hrmanagement:contractworker:add")
    @Log(title = "合同工", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractWorker contractWorker) {
        return toAjax(contractWorkerService.insertContractWorker(contractWorker));
    }

    /**
     * 修改合同工
     */
    @RequiresPermissions("hrmanagement:contractworker:edit")
    @Log(title = "合同工", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractWorker contractWorker) {
        return toAjax(contractWorkerService.updateContractWorker(contractWorker));
    }

    /**
     * 删除合同工
     */
    @RequiresPermissions("hrmanagement:contractworker:remove")
    @Log(title = "合同工", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(contractWorkerService.deleteContractWorkerByIds(ids));
    }


    /**
     * excel 文件导入
     *
     * @param file
     * @throws Exception
     */
//    @RequiresPermissions("hrmanagement:contractworker:import")
    @Log(title = "合同工", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public ResponseData<Object> imp(@RequestParam("file") MultipartFile file) throws Exception {

        //1.使用文件输入流读取文件
        InputStream inputStream = file.getInputStream();
        //2.读取流中的数据
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(inputStream);
        // 手动指定列名和实体类属性的映射
        reader.addHeaderAlias("姓名", "name");
        reader.addHeaderAlias("性别", "gender");
        reader.addHeaderAlias("出生年月", "birthday");
        reader.addHeaderAlias("等级", "grade");
        reader.addHeaderAlias("人员分类", "personnelClassification");
        reader.addHeaderAlias("文化程度", "education");
        reader.addHeaderAlias("主职务", "duty");
        reader.addHeaderAlias("头衔", "title");
        reader.addHeaderAlias("籍贯", "nativePlace");
        reader.addHeaderAlias("民族", "minority");
        reader.addHeaderAlias("入党日期", "joinPartyDate");
        reader.addHeaderAlias("政治面貌", "politicalOutlook");
        reader.addHeaderAlias("全日制学历", "fullTimeQualification");
        reader.addHeaderAlias("全日制学位", "fullTimeDegree");
        reader.addHeaderAlias("全日制毕业院校专业", "fullTimeGraduateSchoolSpecialty");
        reader.addHeaderAlias("在职教育学历", "jobEducationQualification");
        reader.addHeaderAlias("在职教育毕业院校专业", "jobGraduateSchoolSpecialty");
        reader.addHeaderAlias("身份证号", "idCardNumber");
        reader.addHeaderAlias("手机号", "phoneNumber");
        reader.addHeaderAlias("配偶单位", "spousalWorkplace");
        reader.addHeaderAlias("配偶职务", "spousalDuty");
        reader.addHeaderAlias("父母单位", "parentWorkplace");
        reader.addHeaderAlias("父母职务", "parentDuty");
        reader.addHeaderAlias("子女工作单位", "childrenWorkplace");
        reader.addHeaderAlias("子女职务", "childrenDuty");
        reader.addHeaderAlias("正式编制", "formalEstablishment");
        reader.addHeaderAlias("父母姓名", "parentName");
        reader.addHeaderAlias("子女姓名", "childrenName");
        reader.addHeaderAlias("当年公休", "yearPublicHoliday");
        reader.addHeaderAlias("剩余公休", "restPublicHoliday");
        reader.addHeaderAlias("是否删除", "isDeleted");
        reader.addHeaderAlias("是否禁用", "isLocked");

        //3.将读取到的数据填充为List<ContractWorker>
        List<ContractWorker> contractWorkers = reader.readAll(ContractWorker.class);
        System.out.println(contractWorkers);
        // 限制最多读取500行数据
        if (contractWorkers.size() > 500) {
            ResponseData<Object> errorResponse = new ResponseData<>();
            errorResponse.setErrorCode(ResultCode.FILE_SIZE_OUT_OF_RANGE.getCode());
            errorResponse.setMsg(ResultCode.FILE_SIZE_OUT_OF_RANGE.getMessage());
            return errorResponse;
        }

        // 移除所有字段为空的行（即文件末尾的空行）
        contractWorkers.removeIf(this::isAllFieldsEmpty);

        //4.将List导入数据库，并返回导入结果
        return contractWorkerService.insertContractWorkers(contractWorkers);
    }

    // 判断字段是否为空
    private boolean isAllFieldsEmpty(ContractWorker worker) {
        return worker.getName() == null && worker.getGender() == null &&
                worker.getBirthday() == null && worker.getIdCardNumber() == null;
    }
}
